<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose" width="500"
    :close-on-click-modal="false">
    <el-form :model="dialogForm" size="small" :rules="rules" ref="dialogFormRef">
      <el-form-item prop="algoName" label="算例名称">
        <el-input  placeholder="请输入" v-model="dialogForm.algoName" />
      </el-form-item>
      <el-form-item prop="algoCode" label="算例英文名">
        <el-input v-model="dialogForm.algoCode" :disabled="type === 'edit'" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="算例类型" prop="algoType">
        <el-select v-model="dialogForm.algoType" style="width:100%">
          <el-option v-for="item in types" :label="item.name" :value="item.value" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="algoDescribe" label="算例描述">
        <el-input v-model="dialogForm.algoDescribe" placeholder="请输入" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSure">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addAlgo, editAlgo } from "@/api/computingConfig.js";
import { getTemplateTree, getTemplateList, getRulesList, handleTemplateInfo ,deleteTemplateInfo} from "@/api/business";
export default {
  name: "VariableDialog",
  props: {
    datas: {
      type: Object,
      default: () => ({}),
    },
    type: {
      type: String,
      default: "add",
    },
  },
  data() {
    return {
      title: "",
      dialogVisible: true,
      dialogForm: {
        algoName: "",
        algoCode: "",
        templateId: "",
        algoDescribe: "",
        algoType: "",
        resultTemplateId: null
      },
      disabled: false,
      rules: {
        algoName: [
          { required: true, message: "算例名称不能为空", trigger: "blur" },
        ],
        algoCode: [
          { required: true, message: "算例编码不能为空", trigger: "blur" },
        ],
        algoType: [
          { required: true, message: "算例类型不能为空", trigger: "blur" },
        ],
      },
      docInfo: {
        classifyId: 1, //默认放置在全部
        deadlineTime: "2099-11-29T16:00:00.000Z",
        docName: "",
        templateId: "", //空白模板id
      },
      // 模板树
      algoTemplate: [],
      algoTemplateInfo: {},
      stressTemplateId: null,
      types: [{ name: "静强度算法", value: "STATIC_STRENGTH" }],
      algoResultTemplate:[],
      stressResultTemplateId:null
    };
  },
  mounted() {
    this.initData();
    this.initTemplateId();
  },
  methods: {
    initData() {
      if (this.type !== "add") {
        this.dialogForm = {
          id: this.datas.id,
          algoName: this.datas.algoName,
          algoCode: this.datas.algoCode,
          templateId: this.datas.templateId,
          algoDescribe: this.datas.algoDescribe,
          algoType: this.datas.algoType,
          resultTemplateId: this.datas.resultTemplateId,
          resultTemplateVars:this.datas.resultTemplateVars
        };

      }
    },
    // 查询算力模板ID
    initTemplateId() {
      getTemplateTree().then(async res => {
        if (res?.data) {
          this.algoTemplate = await res?.data[0]?.children.filter(item => {
            return item.name.includes('算例库')
          }) || [];
          this.algoResultTemplate = await res?.data[0]?.children.filter(item => {
            return item.name.includes('算例结果库')
          }) || [];
          const tempalteChild = this.algoTemplate[0].children;
          this.stressTemplateId = tempalteChild[0]?.id;
          const resultTempalteChild = this.algoResultTemplate[0].children;
          this.stressResultTemplateId = resultTempalteChild[0]?.id;
        }
      })
    },
    handleClose() {
      this.$emit("on-close");
    },
    handleSure() {
      if(!this.stressResultTemplateId){
        this.$message.errpr("未配置算例结果模板，请先配置算例结果模板！");
        return;
      }
      this.$refs.dialogFormRef.validate(async (valid) => {
        if (valid) {
          if (this.type === "add") {
            // 先增加文章，再绑定文章ID到算例
            const rules = await getRulesList();
            const useRule = rules?.data.filter(item => {
              return item.name === 'BLANK'
            })
            const params = {
              classifyId: this.stressTemplateId,
              languageType: "zh",
              name: this.dialogForm.algoName,
              ruleId: useRule[0].id
            }
            // 查询对应的模板信息
            handleTemplateInfo(params).then(async(res) => {
              if (res?.data) {
                // 查询结果模板
                let resultData=null;
                await getTemplateList({
                  classifyId: this.stressResultTemplateId,
                  pageNum: 1,
                  pageSize: 100
                }).then(async(r)=>{
                  const dataList = r.data.list.map(i => {
                      return {
                        ...i,
                        isPublished: i.status === '1'
                      }
                    })
                    resultData = await dataList.filter(item => {
                      return item.name == '算例结果模板'
                    })
                })
                getTemplateList({
                  classifyId: this.stressTemplateId,
                  pageNum: 1,
                  pageSize: 100
                })
                  .then(async (res) => {
                    const dataList = res.data.list.map(i => {
                      return {
                        ...i,
                        isPublished: i.status === '1'
                      }
                    })
                    const templateInfo = await dataList.filter(item => {
                      return item.name === this.dialogForm.algoName
                    })
                    this.dialogForm.templateId = templateInfo[0].id;
                    this.dialogForm.resultTemplateId = resultData[0].id;
                    // 获取算例结果模板变量
                    const resultVarsStr = localStorage.getItem("resultTemplateVariables");
                    const resultVarsArray = resultVarsStr?.split(',') ||[];
                    this.dialogForm.resultTemplateVars = [...resultVarsArray];
                    addAlgo(this.dialogForm).then((res) => {
                      this.$emit("on-sure");
                      this.$emit("on-close");
                      this.$message.success("添加成功！");
                    }).catch(error=>{
                      // 接口调用失败删除模板
                      deleteTemplateInfo(this.dialogForm.templateId);
                    });
                  })
                  .finally(() => {
                    this.loading = false
                  })

              }
            })
          } else {
            editAlgo(this.dialogForm).then((res) => {
              this.$emit("on-sure");
              this.$emit("on-close");
              this.$message.success("编辑成功！");
            });
          }
        } else {
          this.$message.error("信息填写不完整！");
        }
      });
    },
  },
};
</script>

<style scoped>
.card-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-delete {
  cursor: pointer;
}

.card-delete:hover {
  color: #f00;
}
</style>